/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package experiments;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import services.ConvIntByte;

/**
 *
 * @author minaev
 */
public class DBOutputStream extends OutputStream {

        Connection con;
        Statement s;
        String sql_ins = "INSERT INTO `ser_exp_data` "
                + "(`num_exp`, `ser_obj`) "
                + "VALUES ( 1, '";

        public DBOutputStream() throws ClassNotFoundException, SQLException {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
                    "root", "root");
            s = con.createStatement();
        }

        int count = 0;
        int[] n = new int[6000];
        @Override
        public void write(int b) throws IOException {
            n[count++]=b;
            //sql_ins+=(char)b;
            
            System.out.println("o: "+Integer.toHexString(b));
        }

        @Override
        public void close() throws IOException {
            byte[] nn = new byte[count];
            for (int i = 0; i < count; i++) {
                nn[i] = ConvIntByte.int2Byte(n[i]&0xff);
            }
            sql_ins+=new String(nn);
            sql_ins+="');";
            try {
                s.execute(sql_ins);
            } catch (SQLException ex) {
                Logger.getLogger(SerDBExp.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                s.close();
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(SerDBExp.class.getName()).log(Level.SEVERE, null, ex);
            }
            super.close();
        }
    }